<template>
  <view class="container">
    <!-- 全屏加载动画 -->
    <view class="loading-overlay" v-if="isAnalyzing">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">努力鉴定中...</text>
      </view>
    </view>
    <view class="upload-options">
      <view class="option-item" @click="handleCamera">
        <view class="option-circle camera-bg">
          <image class="option-icon" src="/static/icons/camera.png" mode="aspectFit"></image>
        </view>
        <text class="option-text">拍照</text>
      </view>
      
      <view class="option-item" @click="handleAlbum">
        <view class="option-circle album-bg">
          <image class="option-icon" src="/static/icons/album.png" mode="aspectFit"></image>
        </view>
        <text class="option-text">从相册选择</text>
      </view>
    </view>

    <view class="tips-text">
      <text>清晰正面全身照，更容易获得精准"毒评哦~</text>
    </view>
    
    <!-- 示例展示区 -->
    <view class="example-section">
      <view class="section-title">示例参考</view>
      <view class="example-list">
        <view class="example-item good">
          <image src="/static/demo/good.jpg" mode="aspectFill"></image>
          <text class="label success">推荐</text>
          <text class="desc">清晰全身照</text>
        </view>
        <view class="example-item bad">
          <image src="/static/demo/bad.jpg" mode="aspectFill"></image>
          <text class="label warning">不推荐</text>
          <text class="desc">局部/模糊照片</text>
        </view>
      </view>
    </view>

    <view class="features">
      <view class="feature-item">
        <text class="feature-icon">📊</text>
        <text class="feature-text">光线充足</text>
      </view>
      <view class="feature-item">
        <text class="feature-icon">👤</text>
        <text class="feature-text">全身入镜</text>
      </view>
      <view class="feature-item">
        <text class="feature-icon">🔍</text>
        <text class="feature-text">清晰度高</text>
      </view>
    </view>

    <!-- 温馨提示区域 -->
    <view class="notice-section">
      <view class="notice-title">温馨提示</view>
      <view class="notice-list">
        <view class="notice-item">
          <text class="dot">·</text>
          <text>建议使用最近拍摄的照片</text>
        </view>
        <view class="notice-item">
          <text class="dot">·</text>
          <text>照片仅用于AI分析，不会保存或他用</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import * as UploadApi from '@/api/upload'
import * as DifyApi from '@/api/dify'
export default {
  data() {
    return {
      isAnalyzing: false
    }
  },
  onShow() {
    this.isAnalyzing = false
  },
  methods: {
    // 处理拍照
    handleCamera() {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
          console.log("handleCamera:", res)
          // this.uploadImage(res.tempFilePaths[0])
          this.uploadImage(res.tempFiles[0])
        },
        fail: (err) => {
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 处理相册选择
    handleAlbum() {
      uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: (res) => {
          console.log("handleAlbum:", res)
          // this.uploadImage(res.tempFilePaths[0])
          this.uploadImage(res.tempFiles[0])
        },
        fail: (err) => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 上传图片
    async uploadImage(tempFilePath) {
      try {
        uni.showLoading({
          title: '正在上传...',
          mask: true
        })
        
        // TODO: 实现图片上传到服务器的逻辑
        const result  = await UploadApi.image([tempFilePath])
        const anaRes = await DifyApi.analysis({fileId: result[0].file_id})

        // 定义状态常量
        const STATUS = {
          PENDING: 1,    // 等待分析
          PROCESSING: 2,  // 分析中
          SUCCESS: 3,     // 分析成功
          FAILED: 4,      // 分析失败
          ERROR: 5        // 系统错误
        }
        
        // 轮询检查分析状态
        let retryCount = 0
        const maxRetries = 30 // 最大重试次数
        const retryInterval = 2000 // 重试间隔(ms)
        
        const checkStatus = async () => {
          this.isAnalyzing = true
          try {
            const statusRes = await DifyApi.getRecordStatus({recordId: anaRes.data.recordId})
            console.log('分析状态:', statusRes.data.status)
            
            switch(statusRes.data.status) {
              case STATUS.PENDING:
              case STATUS.PROCESSING:
                if (retryCount < maxRetries) {
                  retryCount++
                  setTimeout(checkStatus, retryInterval)
                } else {
                  uni.hideLoading()
                  uni.showToast({
                    title: '分析超时，请重试',
                    icon: 'none'
                  })
                }
                break
                
              case STATUS.SUCCESS:
                uni.hideLoading()
                uni.navigateTo({
                  url: `/pages/result/result?recordId=${anaRes.data.recordId}`
                })
                break
                
              case STATUS.FAILED:
              case STATUS.ERROR:
                this.isAnalyzing = false
                uni.hideLoading()
                uni.showToast({
                  title: '分析失败，请重试',
                  icon: 'none'
                })
                break
                
              default:
                this.isAnalyzing = false
                uni.hideLoading()
                uni.showToast({
                  title: '未知错误，请重试',
                  icon: 'none'
                })
            }
          } catch (error) {
            console.error('检查状态出错:', error)
            uni.hideLoading()
            uni.showToast({
              title: '网络异常，请重试',
              icon: 'none'
            })
          }
        }
        
        // 开始检查状态
        checkStatus()
        
        console.log("anaRes:", anaRes)
        
        
      } catch (error) {
        console.log("uploadImage error:", error)
        uni.hideLoading()
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #FFF5F7;  // 修改为统一的背景色
  padding: 0 40rpx;
  padding-top: 200rpx;  // 将margin改为padding，避免背景色断层
  position: relative;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #FF7B8C;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #FF7B8C;
  font-size: 32rpx;
  font-weight: bold;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.upload-options {
  display: flex;
  justify-content: center;
  gap: 60rpx;
  margin-top: 0;  // 移除之前的margin-top
  
  .option-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .option-circle {
      width: 180rpx;
      height: 180rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20rpx;
      
      .icon {
        font-size: 60rpx;
      }
    }

    .camera-bg {
      background: #FF7B8C;
    }

    .album-bg {
      background: #4CD4C5;
    }
    
    .option-text {
      font-size: 32rpx;
      color: #333;
      margin-top: 20rpx;
    }
  }
}

.tips-text {
  text-align: center;
  margin: 60rpx 0;
  padding: 20rpx;
  color: #666;
  font-size: 28rpx;
}

.features {
  display: flex;
  justify-content: space-around;
  margin-top: 60rpx;
  
  .feature-item {
    background: #FFFFFF;
    padding: 30rpx 40rpx;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10rpx;
    
    .feature-icon {
      font-size: 40rpx;
    }
    
    .feature-text {
      font-size: 26rpx;
      color: #333;
    }
  }
}

.example-section {
  margin-top: 60rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  padding: 30rpx;

  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .example-list {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;

    .example-item {
      flex: 1;
      position: relative;

      image {
        width: 100%;
        height: 300rpx;
        border-radius: 12rpx;
      }

      .label {
        position: absolute;
        top: 16rpx;
        right: 16rpx;
        padding: 4rpx 12rpx;
        border-radius: 8rpx;
        font-size: 24rpx;
        
        &.success {
          background: #4CD4C5;
          color: #FFF;
        }
        
        &.warning {
          background: #FF7B8C;
          color: #FFF;
        }
      }

      .desc {
        font-size: 26rpx;
        color: #666;
        text-align: center;
        margin-top: 12rpx;
        display: block;
      }
    }
  }
}

.notice-section {
  margin: 40rpx 0;
  padding: 30rpx;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16rpx;

  .notice-title {
    font-size: 28rpx;
    color: #FF7B8C;
    margin-bottom: 16rpx;
  }

  .notice-list {
    .notice-item {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      .dot {
        color: #FF7B8C;
        margin-right: 10rpx;
      }

      text {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}
.upload-options {
  .option-item {
    .option-circle {
      .option-icon {
        width: 64rpx;
        height: 64rpx;
      }
    }
  }
}
</style>